<?php
  // colorize image, used for dyeing clothes
  // FIXME: unfortunately, this image is too slow, it will not be usable on real server
  // FIXME: i want to use html canvas instead but there are problems because image->pixel_manipulation->image is not possible, only image->pixel_manipulation->canvas which is not enough
  // NOTE: compromise might be static cache (convert all images to all colors but that is not very nice, also it will need too many disk space)
  require_once dirname(__FILE__)."/purin2/core/core.php";

  // speed measurement
  $t1 = microtime(true);
  
  // get image name + some security constraints
  $image_filename = @substr($_REQUEST['image'],0,300);                    // limit filename length to 300
  $image_filename = preg_replace('[^a-z0-9_/-]', "", $image_filename);   // allows only a-z 0-9 - _ and /
  $image_filename = "graphics/sprites/$image_filename.png";              // allows only this path and png extension
  $debug = (1*@$_REQUEST['debug']!=0);
  
  // get color koeficients
  $kr = (1*@$_REQUEST['r'])/255;
  $kg = (1*@$_REQUEST['g'])/255;
  $kb = (1*@$_REQUEST['b'])/255;
  if ($debug)
    echo "koef = $kr $kg $kb";

  // load image
  list($width, $height) = @getimagesize($image_filename);
  $image = @imagecreatefrompng($image_filename);
  if ($width <= 0)
    die("error: image '$image_filename' not found or not valid png image!");

  // set transparent color (upper left corner)
  $tr = imagecolorat($image,0,0);
  imagecolortransparent($image,$tr);
  if ($debug)
    echo " tr=$tr w=$width h=$height ";

  // multiply RGB channels by given RGB coeficients
  for ($y=0; $y<$height; $y++) 
    for ($x=0; $x<$width; $x++) {
      // get pixel color
      $rgb = imagecolorat($image,$x,$y);
      if ($rgb == $tr) 
        continue;
      $a = ($rgb >> 24) & 0xFF;
      $b = ($rgb >> 16) & 0xFF;
      $g = ($rgb >> 8) & 0xFF;
      $r = $rgb & 0xFF;
      // dye only gray part  
      if ( ($r!=$g)||($r!=$b) )
        continue;
      // color change
      $r = floor($kb * $r);      if ($r > 255) $r = 255;
      $g = floor($kg * $g);      if ($g > 255) $g = 255;
      $b = floor($kr * $b);      if ($b > 255) $b = 255;
      // set new color
      $n = ($a << 24) + ($b << 16) + ($g << 8) + $r;
      imagesetpixel($image,$x,$y,$n);
    }

  // output image
  if (!$debug) {
    header('Content-Type: image/png');
    imagepng($image);
  } else {
    // save modified image
    imagepng($image,'hue2.png');
    echo "time = ".(microtime(true)-$t1).' seconds';
    echo "<img src=\"$image_filename\" />";
    echo "<img src=\"hue2.png\" />";
  }
  
?>